export interface Info {
  id: string;
  username: string;
  gender: boolean;
  nickname: string;
  phone: string;
  email: string;
  avatar: string;
  rememberMe: boolean;
  ip: string;
  /**
   * @deprecated
   **/
  roles: string[];
  /**
   * @deprecated
   **/
  accesses: string[];
  authorities: string[];
  time: string | null;
}

/**
 * @deprecated
 **/
export interface Authority {
  roles: string[];
  accesses: string[];
}

/**
 * @author 戴俊明 <idaijunming@163.com>
 * @description 账户的角色只要拥有要求中的一个即通过
 * @description 账户的权限需要要拥有要求中的所有权限才能通过
 * @date 2019/11/26 16:48
 * @param roles 需要的角色
 * @param accesses 需要的权限
 * @param info 账户信息
 **/
/**
 * @deprecated
 **/
export const isAllowed = (roles: string[], accesses: string[], info: Info): boolean => {
  const accountRoles = info.roles ? info.roles : [];
  const accountPerms = info.accesses ? info.accesses : [];
  if (roles.length > 0) {
    if (accesses.length > 0) {
      return accountRoles.some(item => roles.includes(item)) && accesses.every(item => accountPerms.includes(item));
    } else {
      return accountRoles.some(item => roles.includes(item));
    }
  } else if (accesses.length > 0) {
    return accesses.every(item => accountPerms.includes(item));
  } else {
    return true;
  }
};

export const authenticate = (requireAuthorities: string[], authorities: string[]): boolean => {
  const temp = authorities.filter(v => v.includes('*'));
  for (const a of requireAuthorities) {
    if (!authorities.includes(a)) {
      let flag = false;
      for (const b of temp) {
        if (new RegExp(b.replace('*', '\\w')).test(a)) {
          flag = true;
          break;
        }
      }
      if (!flag) {
        return false;
      }
    }
  }
  return true;
};
